﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Zyg.SSO.Core.Business;

namespace Zyg.SSO.Web.Admin.App
{
    public partial class AddApp : Zyg.SSO.Web.BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!base.Account.HavePermission(Permission.AppManage))
                {
                    throw new Exception("你无权查看此页面");
                }
            }
        }

        protected void BtnSubmit_Click(object sender, EventArgs e)
        {
            Zyg.SSO.Core.Business.App app = new Zyg.SSO.Core.Business.App();

            app.Id = Guid.NewGuid();
            app.IP = AppIP.Text;
            app.LoginFile = AppLoginFileAddress.Text;
            app.Name = AppName.Text;

            if (!string.IsNullOrEmpty(AppPort.Text))
                app.Port = int.Parse(AppPort.Text);

            app.Url = AppUrl.Text;

            if (AppPicture.HasFile)
            {
                string accountContentPath = Server.MapPath("~/Content/App/");
                string extension = Zyg.Utility.Helper.FileHelper.GetFileExtension(AppPicture.FileName);

                string fileName = app.Id.ToString() + extension;

                app.PictureAddress = "~/Content/App/" + fileName;

                AppPicture.SaveAs(accountContentPath + fileName);
            }

            app.Save();

            Zyg.SSO.Core.Business.Log log = new Zyg.SSO.Core.Business.Log();
            log.AccountId = base.Account.Id;
            log.ModuleId = Zyg.SSO.Core.Business.Module.App.Id;
            log.Message = string.Format("管理员 {0} 添加了应用系统 {1}", base.Account.Email, app.Name);

            log.Save();

            WriteBackScript("alert('添加应用系统成功');window.location.href='AppList.aspx';");

        }
    }
}
